import { fetchEventSource } from "@microsoft/fetch-event-source";

// 终止请求控制器
const abortController = new AbortController();
/**
 * url 后端请求地址
 * params 请求参数
 * callback 回调函数
 * 说明：callback中的status状态为以下四种：
 * connect 连接成功
 * running 输出中
 * stop 用户手动停止
 * end 程序自己停止
 *
 **/
export const initFetchEventSource = async (url, params, callback) => {
  await fetchEventSource(import.meta.env.VITE_APP_BASE_API + url, {
    method: "POST",
    headers: {
      "Content-Type": "application/json;charset=utf-8",
      "Accept": "text/event-stream"
    },
    body: JSON.stringify(params),
    openWhenHidden: true,
    signal: abortController.signal,
    onopen: (res) => {
      if (res.ok) {
        console.log("连接成功");
        callback({ status: "connect", abortController });
      } else {
        callback({ data: "暂无数据。", status: "fail" });
      }
    },
    onmessage: (msg) => {
      if (msg.event === "FatalError") {
        throw new Error(msg.data);
      }
      if (msg.data !== "[DONE]") {
        callback({ data: msg.data, status: "running" });
      }
    },
    onclose: () => {
      console.log("连接关闭");
      // 回调会话结束通知
      callback({ data: "", status: "end" });
    },
    onerror: (err) => {
      throw new Error(err);
    }
  });
};
